package org.snusmumr.android.media.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.snusmumr.android.media.Constants;

import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseManager extends SQLiteOpenHelper {
	private static final String LOG_TAG = DatabaseManager.class.getName();
	public static final String DB_NAME = "mediacatalog.db";
	private Context context;

	public DatabaseManager(Context context, CursorFactory factory) {
		super(context, DB_NAME, factory, Constants.DB_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			createDB(db);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void createDB(SQLiteDatabase db) throws IOException {
		Resources res = context.getResources();
		BufferedReader reader = null;
		try {
			InputStream is = res.getAssets().open("update_0.sql");
			reader = new BufferedReader(new InputStreamReader(is));
			String row;
			String query = "";
			while ((row = reader.readLine()) != null) {
				query += row;
				if(query.trim().endsWith(";")) {
					// execute query;
					Log.d(LOG_TAG, "create db: " + query);
					db.execSQL(query);
					
					// set query = empty
					query = "";
				} else if(! query.endsWith(" "))
					query += " ";
			}
		} finally {
			if(reader != null)
					reader.close();
		}
	}
	

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}
